﻿using Meiam.System.Common.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceProcess;

namespace GetMesService
{
    public partial class Service1 : ServiceBase
    {
        //日志地址
        private string strLogPath = System.Configuration.ConfigurationManager.AppSettings["LogPath"];
        //文件保存路径
        //定时时间
        private double hour = double.Parse(System.Configuration.ConfigurationManager.AppSettings["hourvalue"]);
        private double min = double.Parse(System.Configuration.ConfigurationManager.AppSettings["minvalue"]);
        //当前数据库连接
        private string curSysDb_conn = string.Empty;
        string timer_Upload = System.Configuration.ConfigurationManager.AppSettings["Timer_Upload"];
        public Service1()
        {
            InitializeComponent();
        }
        #region 日志记录方法
        private void WriteAllLogs(string message, bool isError, string dir)
        {
            //this.EventLog.WriteEntry(message);
            this.WriteLogTXT(message);
        }

        /// <summary>
        /// 文本日志记录
        /// </summary>
        /// <param name="logStr">日志内容</param>
        private void WriteLogTXT(string logStr)
        {
            System.IO.StreamWriter writer = null;
            try
            {
                string strcLogPath = strLogPath;//日志文件路径;
                if (!Directory.Exists(strcLogPath))
                {
                    Directory.CreateDirectory(strcLogPath);
                }
                strcLogPath += DateTime.Now.Date.ToString("yyyy-M-dd") + "_错误日志.txt";
                logStr = DateTime.Now.ToShortTimeString() + "     " + logStr;
                writer = System.IO.File.AppendText(strcLogPath);
                writer.WriteLine(logStr);
                writer.WriteLine();
            }
            catch (Exception)
            {
                //this.EventLog.WriteEntry(logStr);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
        #endregion
        protected override void OnStart(string[] args)
        {
            try
            {
                //记录开始时间
                WriteAllLogs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   获取MES投料数据服务启动。", false, "获取MES投料数据服务 MainService.OnStart");
                //获取配置的计时器分钟
              
                //根据获取的结果来设置并启动计时器。如果时长为0，则不启动计时器。
                if (timer_Upload != "0")
                {
                    //setTaskAtFixedTime();
                    ////这里控制单位，Interval接受的毫秒ms  timer_Upload的单位是分钟
                    Timer_Upload.Interval = double.Parse(timer_Upload) * 1000 * 60;
                    Timer_Upload.Start();
                }
                else
                {
                    Timer_Upload.Enabled = false;
                }

            }
            catch (Exception ee)
            {
                WriteAllLogs(ee.ToString(), true, "获取MES投料数据服务 MainService.OnStart");
            }
        }

        /// <summary>
        /// 定时设置
        /// </summary>
        private void setTaskAtFixedTime()
        {
            try
            {
                DateTime now = DateTime.Now;
                DateTime oneOClock = DateTime.Today.AddHours(hour).AddMinutes(min); //获取定时时间
                if (now > oneOClock)
                {
                    oneOClock = oneOClock.AddDays(1.0);
                }
                int msUntilFour = (int)((oneOClock - now).TotalMilliseconds);

                Timer_Upload.Interval = msUntilFour;
                Timer_Upload.Start();
                WriteAllLogs("当前时间:" + now.ToString("yyyy-MM-dd HH:mm:ss") + "距离下次执行还有" + msUntilFour.ToString() + "毫秒", false, "定时设置");
            }
            catch (Exception ex)
            {

                WriteAllLogs("设定时间执行失败，原因：" + ex.Message.ToString(), false, "定时设置");
            }

        }

        protected override void OnStop()
        {
            //关闭计时器
            Timer_Upload.Enabled = false;
            // 执行停止服务所需的关闭操作。
            WriteAllLogs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   获取MES投料数据服务关闭。", false, "获取MES投料数据服务 MainService.OnStop");
        }

        /// <summary>
        /// 实际执行逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Upload_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Timer_Upload.Enabled = false;
            /*
             * 调用接口获取数据 
             */
            GetMesJWData();
        }

        /// <summary>
        /// 获取金湾数据
        /// </summary>
        private void GetMesJWData()
        {
           
            //string strDate = string.Empty;
            string strRandomstr = string.Empty;
            string strUrl = System.Configuration.ConfigurationManager.AppSettings["url"];
            //数据库连接串
            string sysDb_conn = System.Configuration.ConfigurationManager.AppSettings["sgs_connStr"];
            //用户账号
            string strUser = System.Configuration.ConfigurationManager.AppSettings["UserName"];
            
            //接口用数据如下
            try
            {
                //[20211216 shb add] 判断token是否存在 start
                //token存在，使用作为请求参数，不存在则重新请求
                //rtn = RedisServer.Session.HGet("9999", "F375083D-7AB3-4B16-9321-98E0927F1ED7");
                //Dictionary<string, string> list = RedisServer.Session.HGetAll("9999");
                //string strkey = string.Empty;
                //string strvalue = string.Empty;
                //foreach (var item in list)
                //{
                //    strkey = item.Key;
                //    strvalue = item.Value;
                //}
                //[20211216 shb add] 判断token是否存在 end
                //日期获取
                ////strDate = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                //todo 这里设置到前一天到今天的数据同步
                string strparadate = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                this.WriteLogTXT("请求参数：" + strparadate + "执行当前时间：" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //***接口调用***
                //var res = HTTPHelpers.PostResponse(strUrl, strparadate);
                var res = HttpsRequest.PostHttpsRequestBody(strUrl, strparadate);
                this.WriteLogTXT("结果：" + res);
                //解析，成功写入主表数据并下载excel 失败返回结果
                //T_InterfaceRtn rtnobj = new T_InterfaceRtn();
                //rtnobj = JsonConvert.DeserializeObject<T_InterfaceRtn>(res);

            }
            catch (Exception ex)
            {
                this.WriteLogTXT("GetExcelfile()异常，原因：" + ex.Message.ToString());
            }
        }
    }
}
